﻿using Matthew.DBManager;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Security.Principal;
using System.Web;
using System;
using System.Diagnostics;

namespace MvcApplicationTest.Controllers
{
    public class Utility
    {
        public static EventLog logger = new EventLog("Order System");
        public static bool ValidateUser(string userName, string userPsw)
        {
            UserInfo userInfo = DataBaseManager.GetUserInfo(userName, false);
            if (userPsw.Equals(userInfo.UserPsw))
            {
                return true;
            }
            return false;
        }

        public static bool ChangeUserPsw(string userName, string oldPsw, string newPsw)
        {
            UserInfo userInfo = DataBaseManager.GetUserInfo(userName, false);
            if (oldPsw.Equals(userInfo.UserPsw))
            {
                if (DataBaseManager.ChangeUserPassWord(userName, newPsw))
                {
                    var user = new CacheUser();
                    user.ChangePwdOfCacheUser(newPsw);
                    return true;
                }
            }
            return false;
        }

        public static bool CheckUserNameExist(string userName)
        {
            if (string.IsNullOrEmpty(DataBaseManager.GetUserInfo(userName, false).UserName))
            {
                return false;
            }
            return true;
        }

        public static bool ChangeUserPswOrDisplay(string userName, string password, string displayName)
        {
            var user = DataBaseManager.GetUserInfo(userName, false);
            user.UserPsw = password;
            user.DisplayName = displayName;
            var httpUser = new CacheUser();
            if (httpUser.PassWord != password)
            {
                httpUser.ChangePwdOfCacheUser(password);
            }
            return DataBaseManager.ChangeUserInfo(user);
        }

        public static bool RegisterUser(string userName, string userPsw, string displayName)
        {
            if (CheckUserNameExist(userName))
            {
                return false;
            }
            if ("jnwu".Equals(userName))
            {
                bool insertAdminInfo = DataBaseManager.InsertAdminManagerInfo(userName, false);
                return insertAdminInfo && DataBaseManager.AddUserInfo(new UserInfo() { UserName = userName, DisplayName = displayName, UserPsw = userPsw, UserBalance = 0, UserRole = "Admin" });
            }
            return DataBaseManager.AddUserInfo(new UserInfo() { UserName = userName, DisplayName = displayName, UserPsw = userPsw, UserBalance = 0, UserRole = "User" });
        }

        public static List<UserInfo> GetAllUserInfo()
        {
            //不能查orders
            return DataBaseManager.GetUserInfo();
        }

        public static List<UserInfo> GetAllOrdersByFlagDay(string flagDay)
        {
            return DataBaseManager.GetOrdersByFlagDay(flagDay);
        }

        public static void GetSelectedExpectedOrderShops(string userName, string flagDay, List<SelectListItem> lists)
        {
            foreach (var expected in DataBaseManager.GetUserSpecialExpectedOrder(userName, flagDay).UserExpecteds)
            {
                var item = lists.Find(m => ConvertToOrdersIntEnum(m.Value) == expected);
                if (item != null)
                {
                    item.Selected = true;
                }
            }
        }

        public static bool AddOrderForUser(string userName, List<SelectedOrderItem> orderLists, string orderTime, string flagDay)
        {
            if (orderLists.Count > 0)
            {
                UserInfo info = DataBaseManager.GetUserInfo(userName, false);
                if (info.UserBalance < 0)
                {
                    return false;
                }
                info.UserOrderInfos = new List<UserOrderInfo>();
                int cost = 0;
                foreach (var list in orderLists)
                {
                    logger.Source = "Order System Source";
                    logger.WriteEntry(string.Format("Add order, user:{0}, order:{1}, cost:{2}", userName, list.OrderValue, list.OrderCost), EventLogEntryType.Information);
                    cost += list.OrderCost;
                    info.UserOrderInfos.Add(new UserOrderInfo() { UserOrder = list.OrderValue, UserOrderTime = orderTime, UserCost = list.OrderCost, FlagDay = flagDay });
                }
                //有可能为负数的balance
                info.UserBalance = info.UserBalance - cost;

                return InsertOrderDataToDB(info, false, cost);
            }
            return true;
        }

        public static bool DeleteOrderForUser(string userName, List<SelectedOrderItem> orderLists, string flagDay)
        {
            if (orderLists.Count > 0)
            {
                UserInfo info = DataBaseManager.GetUserInfo(userName, false);
                info.UserOrderInfos = new List<UserOrderInfo>();
                int cost = 0;
                foreach (var list in orderLists)
                {
                    logger.Source = "Order System Source";
                    logger.WriteEntry(string.Format("Delete order, user:{0}, order:{1}, cost:{2}", userName, list.OrderValue, list.OrderCost), EventLogEntryType.Information);
                    cost += list.OrderCost;
                    info.UserOrderInfos.Add(new UserOrderInfo() { UserOrder = list.OrderValue, UserCost = list.OrderCost, FlagDay = flagDay, UserOrderTime = list.OrderTime });
                }
                info.UserBalance = info.UserBalance + cost;
                return InsertOrderDataToDB(info, true, cost);
            }
            return true;
        }

        //isAdd表示，是否给user加钱
        private static bool InsertOrderDataToDB(UserInfo info, bool isAdd, int cost)
        {
            if (isAdd)
            {
                //补钱先删订单再补钱
                if (DataBaseManager.DeleteUserOrderInfo(info.UserName, info.UserOrderInfos))
                {
                    if (!DataBaseManager.ChangeUserInfo(info))
                    {
                        logger.WriteEntry(string.Format("Delete order error, user:{0}, cost:{1} ", info.UserName, cost), EventLogEntryType.Error);
                        //订单删了钱没补上
                        return false;
                    }
                    return true;
                }
                return false;
            }
            else
            {
                //订餐先扣钱再订
                if (DataBaseManager.ChangeUserInfo(info))
                {
                    if (!DataBaseManager.AddUserOrderInfo(info.UserName, info.UserOrderInfos))
                    {
                        logger.WriteEntry(string.Format("Add order error, user:{0}, cost:{1} ", info.UserName, cost), EventLogEntryType.Error);
                        //钱扣了饭没订上需要处理，最好能打log
                        return false;
                    }
                    return true;
                }
                return false;
            }
        }

        public static bool UpdateExpectedData(string userName, List<SelectListItem> lists, string flagDay)
        {
            if (DataBaseManager.GetUserSpecialExpectedOrder(userName, flagDay).UserExpecteds.Count > 0)
            {
                if (!DataBaseManager.DeleteUserExpected(userName, flagDay))
                {
                    return false;
                }
            }
            if (lists.Count == 0)
                return true;

            return InsertExpectedDataToDB(userName, lists, flagDay);
        }

        public static bool UpdateAdministratorInfo(bool ifCanOrder, Orders shop)
        {
            var info = DataBaseManager.GetAdminManagerInfo();
            info.IfCanOrder = ifCanOrder;
            string flagDay = DateTime.Now.ToString("yyyyMMdd");
            if (shop == Orders.Nothing)
            {
                info.WhatToEat = DataBaseManager.GetMostExpectedOrders(flagDay)[0].Shop;
            }
            else
            {
                info.WhatToEat = shop;
            }
            return DataBaseManager.UpdateAdminManagerInfo(info);
        }

        public static void GetMostExpectedOrders()
        {
            string flagDay = DateTime.Now.ToString("yyyyMMdd");
            var result = DataBaseManager.GetMostExpectedOrders(flagDay);
            //foreach (var item in result)
            //{ 
            //    item.Shop}
        }

        public static bool InsertExpectedDataToDB(string userName, List<SelectListItem> lists, string flagDay)
        {
            List<int> expects = new List<int>();
            lists.ForEach(m => expects.Add(ConvertToOrdersIntEnum(m.Value)));
            return DataBaseManager.AddUserExpected(userName, expects, flagDay);
        }

        private static int ConvertToOrdersIntEnum(string shop)
        {
            switch (shop)
            {
                case "Kuaicanxiaozi":
                    return 1;
                case "Meishimeike":
                    return 2;
                default:
                    return 0;
            }
        }

        public static Orders ConvertToOrdersEnum(string shop)
        {
            switch (shop)
            {
                case "Kuaicanxiaozi":
                    return Orders.Kuaicanxiaozi;
                case "Meishimeike":
                    return Orders.Meishimeike;
                default:
                    return Orders.Nothing;
            }
        }

        public static string ConvertStringToDisplay(string shop)
        {
            switch (shop)
            {
                case "Kuaicanxiaozi":
                    return "快餐小子";
                case "Meishimeike":
                    return "美食美客";
                default:
                    return null;
            }
        }

        public static MvcHtmlString CheckBoxListFor(string name, List<SelectedOrderItem> items)
        {
            var str = new StringBuilder();
            str.Append(@"<div class=""checkboxlist"">");
            foreach (var item in items)
            {
                str.Append(@"<div class=""list""><input type=""checkbox"" name=""");
                str.Append(name);
                str.Append("\" value=\"");
                str.Append(item.OrderValue);
                str.Append("\"");
                str.Append(" cost=\"");
                str.Append(item.OrderCost);
                str.Append("\"");
                if (item.Selected)
                    str.Append(@" checked=""checked""");
                str.Append(" />  ");
                str.Append(item.OrderText).Append("  ").Append(item.OrderCost);
                str.Append("</div>");
            }
            str.Append("</div>");

            return MvcHtmlString.Create(str.ToString());
        }

        //此方法仅限which you want使用（在方法内加入href）
        public static MvcHtmlString CheckBoxListFor(string name, List<SelectListItem> items)
        {
            var str = new StringBuilder();
            str.Append(@"<div class=""checkboxlist"">");
            foreach (var item in items)
            {
                str.Append(@"<div class=""list""><input type=""checkbox"" name=""");
                str.Append(name);
                str.Append("\" value=\"");
                str.Append(item.Value);
                str.Append("\"");
                if (item.Selected)
                    str.Append(@" checked=""checked""");
                str.Append(" />");
                str.Append("<a href=\"/Home/ShopPage/");
                str.Append(item.Value);
                str.Append("\">");
                str.Append(item.Text);
                str.Append("</a>");
                str.Append("</div>");
            }
            str.Append("</div>");

            return MvcHtmlString.Create(str.ToString());
        }

        public static List<SelectedOrderItem> GetSelectedOrderItems(string str)
        {
            string[] strSplit = str.Split(',');
            var result = new List<SelectedOrderItem>();
            if (!string.IsNullOrEmpty(str))
            {
                foreach (var split in strSplit)
                {
                    string[] list = split.Split('|');
                    string orderTime = string.Empty;
                    if (list.Length == 3)
                    {
                        orderTime = list[2];
                    }

                    var item = new SelectedOrderItem
                    {
                        OrderValue = list[0],
                        OrderCost = Convert.ToInt32(list[1]),
                        OrderTime = orderTime,
                        Selected = true
                    };
                    result.Add(item);
                }
            }
            return result;
        }

        public static List<SelectListItem> GetSelectedListItems(string str)
        {
            string[] strSplit = str.Split(',');
            var result = new List<SelectListItem>();
            if (!string.IsNullOrEmpty(str))
            {
                foreach (var split in strSplit)
                {
                    string[] list = split.Split('|');
                    var item = new SelectListItem
                    {
                        Value = list[0],
                        Text = list[1],
                        Selected = true
                    };
                    result.Add(item);
                }
            }
            return result;
        }

        public static MvcHtmlString DisPlayOrderInfos(List<UserOrderInfo> userOrderInfos)
        {
            var str = new StringBuilder();
            str.Append(@"<div class=""checkboxlist"">");
            foreach (var list in userOrderInfos)
            {
                str.Append(@"<div class=""list""><input type=""checkbox"" name=""");
                str.Append("DisPlayedOrder");
                str.Append("\" userorder=\"");
                str.Append(list.UserOrder);
                str.Append("\"");
                str.Append(" ordertime=\"");
                str.Append(list.UserOrderTime);
                str.Append("\"");
                str.Append(" cost=\"");
                str.Append(list.UserCost);
                str.Append("\"");
                str.Append(" />");
                str.Append(list.UserOrder).Append(" at ").Append(list.UserOrderTime).Append(" cost: ").Append(list.UserCost);
                str.Append("</div>");
            }
            str.Append("</div></ br>");
            return MvcHtmlString.Create(str.ToString());
        }

        public static MvcHtmlString DisPlayMessageOnBoard(string message, string displayName)
        {
            var str = new StringBuilder();
            str.Append("<li>").Append(message).Append(".----").Append(displayName).Append("</li>");
            return MvcHtmlString.Create(str.ToString());
        }

        public static MvcHtmlString SearchResultOfUser(string userName)
        {
            var str = new StringBuilder();
            if (!string.IsNullOrEmpty(userName))
            {
                //str.Append(@"<div class=""text"">");
                foreach (var list in DataBaseManager.GetUserInfoFromUserNameOrDisplayName(userName))
                {
                    str.Append(@"<div class=""list"">");
                    str.Append("<li>User Name: ").Append(list.UserName).Append("</li>");
                    str.Append("<li>Display Name: ").Append(list.DisplayName).Append("</li>");
                    str.Append("<li>Role: ").Append(list.UserRole).Append("</li>");
                    str.Append("User Balance:");
                    str.Append(@"<input type=""text"" name=""");
                    str.Append("UserSearchResult");
                    str.Append("\" username=\"");
                    str.Append(list.UserName);
                    str.Append("\"");
                    str.Append(" displayname=\"");
                    str.Append(list.DisplayName);
                    str.Append("\"");
                    str.Append(" userrole=\"");
                    str.Append(list.UserRole);
                    str.Append("\"");
                    str.Append(" value=\"");
                    str.Append(list.UserBalance);
                    str.Append("\"");
                    str.Append(" />");
                    str.Append("</div></ br>");
                }
                //str.Append("</div></ br>");
            }
            return MvcHtmlString.Create(str.ToString());
        }

        public static MvcHtmlString SearchResultOfUser()
        {
            var str = new StringBuilder();
            foreach (var list in DataBaseManager.GetUserInfo())
            {
                str.Append(@"<div class=""list"">");
                str.Append("<li>User Name: ").Append(list.UserName).Append("</li>");
                str.Append("<li>Display Name: ").Append(list.DisplayName).Append("</li>");
                str.Append("<li>Role: ").Append(list.UserRole).Append("</li>");
                str.Append("User Balance:");
                str.Append(@"<input type=""text"" name=""");
                str.Append("UserSearchResult");
                str.Append("\" username=\"");
                str.Append(list.UserName);
                str.Append("\"");
                str.Append(" displayname=\"");
                str.Append(list.DisplayName);
                str.Append("\"");
                str.Append(" userrole=\"");
                str.Append(list.UserRole);
                str.Append("\"");
                str.Append(" value=\"");
                str.Append(list.UserBalance);
                str.Append("\"");
                str.Append(" />");
                str.Append("</div></ br>");
            }
            return MvcHtmlString.Create(str.ToString());
        }

        public static MvcHtmlString GetDateTime(string flagDay)
        {
            //"20130726"
            var str = new StringBuilder();
            string mon = flagDay.Substring(4, 2);
            string day = flagDay.Substring(6, 2);
            string year = flagDay.Substring(2, 2);
            str.Append(mon).Append(".").Append(day).Append(".").Append(year);
            return MvcHtmlString.Create(str.ToString());
        }

        public static bool ChangeUserBalance(string userName, string userBalance)
        {
            try
            {
                int balance = Convert.ToInt32(userBalance);
                return DataBaseManager.ChangeUserBalance(userName, balance);
            }
            catch { return false; }

        }

        public static List<SelectListItem> GetAllShopLists()
        {
            //DataBaseManager.get
            var orders = new List<SelectListItem>   
            {  
                new SelectListItem { Value = "Kuaicanxiaozi", Text="快餐小子", Selected = false },  
                new SelectListItem { Value = "Meishimeike", Text="美食美客",Selected = false },  
                new SelectListItem { Value = "shop3", Text="shop3",Selected = false },  
                new SelectListItem { Value = "shop4", Text="shop4",Selected = false },  
            };
            return orders;
        }

        public static List<SelectedOrderItem> GetTodayOrderList(Orders order)
        {
            //DataBaseManager.get
            List<SelectedOrderItem> orders = new List<SelectedOrderItem>();
            switch (order)
            {
                case Orders.Kuaicanxiaozi:
                    orders = new List<SelectedOrderItem>   
            {  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="营养套餐",  OrderValue="营养套餐", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="木耳炒鸡蛋",  OrderValue="木耳炒鸡蛋", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="酸辣土豆丝",  OrderValue="酸辣土豆丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="西红柿鸡蛋",  OrderValue="西红柿鸡蛋", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="肉末茄子",  OrderValue="肉末茄子", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="地三鲜",  OrderValue="地三鲜", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="干煸芸豆",  OrderValue="干煸芸豆", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="鱼香肉丝",  OrderValue="鱼香肉丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="孜然鸡片",  OrderValue="孜然鸡片", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="山野小炒菜",  OrderValue="山野小炒菜", Selected = false }, 
            };
                    break;
                case Orders.Meishimeike:
                    #region
                    orders = new List<SelectedOrderItem>   
            {  
                new SelectedOrderItem {  OrderCost = 7,  OrderText="麻辣豆腐",  OrderValue="麻辣豆腐", Selected = false },  
                new SelectedOrderItem {  OrderCost = 7,  OrderText="尖椒土豆丝",  OrderValue="尖椒土豆丝", Selected = false }, 
                
                new SelectedOrderItem {  OrderCost = 8,  OrderText="地三鲜",  OrderValue="地三鲜", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="豆腐烧肉",  OrderValue="豆腐烧肉", Selected = false },
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="红烧茄子",  OrderValue="红烧茄子", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="肉沫烧茄子",  OrderValue="肉沫烧茄子", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="芸豆烧土豆",  OrderValue="芸豆烧土豆", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="酱炒鸡蛋",  OrderValue="酱炒鸡蛋", Selected = false },
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="尖椒炒鸡蛋",  OrderValue="尖椒炒鸡蛋", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="肉沫豆腐",  OrderValue="肉沫豆腐", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="西红柿鸡蛋",  OrderValue="西红柿鸡蛋", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="干煸芸豆",  OrderValue="干煸芸豆", Selected = false },
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="蒜苔炒鸡蛋",  OrderValue="蒜苔炒鸡蛋", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="韭菜炒鸡蛋",  OrderValue="韭菜炒鸡蛋", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="木耳炒鸡蛋",  OrderValue="木耳炒鸡蛋", Selected = false }, 
               
                new SelectedOrderItem {  OrderCost = 9,  OrderText="木须肉",  OrderValue="木须肉", Selected = false },
                 new SelectedOrderItem {  OrderCost = 9,  OrderText="火腿玉米粒",  OrderValue="火腿玉米粒", Selected = false },  
                new SelectedOrderItem {  OrderCost = 9,  OrderText="鱼香肉丝",  OrderValue="鱼香肉丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 9,  OrderText="辣炒芸豆鸡丁",  OrderValue="辣炒芸豆鸡丁", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 9,  OrderText="土豆鸡丁",  OrderValue="土豆鸡丁", Selected = false },
                 new SelectedOrderItem {  OrderCost = 9,  OrderText="橄榄肉末芸豆",  OrderValue="橄榄肉末芸豆", Selected = false },  
                
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="口水鸡",  OrderValue="口水鸡", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="孜然牛肉",  OrderValue="孜然牛肉", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="红烧鸡块",  OrderValue="红烧鸡块", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="糖醋里脊",  OrderValue="糖醋里脊", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="回锅肉",  OrderValue="回锅肉", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="红烧牛肉",  OrderValue="红烧牛肉", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="咖喱炸鸡",  OrderValue="咖喱炸鸡", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="老干妈牛肉",  OrderValue="老干妈牛肉", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="京酱肉丝",  OrderValue="京酱肉丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="咖喱牛肉",  OrderValue="咖喱牛肉", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="金针肥牛",  OrderValue="金针肥牛", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="牛肉爆头菜",  OrderValue="牛肉爆头菜", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="香辣肉丝",  OrderValue="香辣肉丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="黑椒鸡腿",  OrderValue="黑椒鸡腿", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="秘制炸鸡",  OrderValue="秘制炸鸡", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="香辣牙签肉",  OrderValue="香辣牙签肉", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="孜然肉丝",  OrderValue="孜然肉丝", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="特色鸡腿",  OrderValue="特色鸡腿", Selected = false }, 
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="飘香鸡块",  OrderValue="飘香鸡块", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="尖椒炒牛肉",  OrderValue="尖椒炒牛肉", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="宫保鸡丁",  OrderValue="宫保鸡丁", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="香辣鸡腿",  OrderValue="香辣鸡腿", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="孜然鸡块",  OrderValue="孜然鸡块", Selected = false }, 
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="番茄土豆牛肉",  OrderValue="番茄土豆牛肉", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="辣子鸡丁",  OrderValue="辣子鸡丁", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="沙拉鸡腿",  OrderValue="沙拉鸡腿", Selected = false }, 
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="回锅肘肉",  OrderValue="回锅肘肉", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="番茄土豆鸡肉",  OrderValue="番茄土豆鸡肉", Selected = false },
                 new SelectedOrderItem {  OrderCost = 10,  OrderText="焦溜里脊",  OrderValue="焦溜里脊", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="孜然里脊",  OrderValue="孜然里脊", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 10,  OrderText="红烧肘肉",  OrderValue="红烧肘肉", Selected = false }, 

                 new SelectedOrderItem {  OrderCost = 6,  OrderText="一品豆腐(凉菜)",  OrderValue="一品豆腐(凉菜)(凉菜)", Selected = false }, 
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="炝拌土豆丝(凉菜)",  OrderValue="炝拌土豆丝(凉菜)", Selected = false },  
                new SelectedOrderItem {  OrderCost = 8,  OrderText="葱油豆皮(凉菜)",  OrderValue="葱油豆皮(凉菜)", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="拌三丁(凉菜)",  OrderValue="拌三丁(凉菜)", Selected = false }, 
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="老醋三样(凉菜)",  OrderValue="老醋三样(凉菜)", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 8,  OrderText="皮蛋豆腐(凉菜)",  OrderValue="皮蛋豆腐(凉菜)", Selected = false },
                 new SelectedOrderItem {  OrderCost = 8,  OrderText="川拌凉粉(凉菜)",  OrderValue="川拌凉粉(凉菜)", Selected = false },  
                new SelectedOrderItem {  OrderCost = 10,  OrderText="葱油木耳花生(凉菜)",  OrderValue="葱油木耳花生(凉菜)", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 12,  OrderText="黄瓜金针菇(凉菜)",  OrderValue="黄瓜金针菇(凉菜)", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 14,  OrderText="口水鸡(凉菜)",  OrderValue="口水鸡(凉菜)", Selected = false }, 

                new SelectedOrderItem {  OrderCost = 12,  OrderText="冷面",  OrderValue="冷面", Selected = false }, 
                new SelectedOrderItem {  OrderCost = 12,  OrderText="干拌冷面",  OrderValue="干拌冷面", Selected = false }, 
            };
                    break;
                    #endregion
            }
            return orders;
        }

        public static MvcHtmlString GetOrderPicture(string order)
        {
            var str = new StringBuilder();
            return MvcHtmlString.Create(str.ToString());
        }

        public static bool CheckUserOrder(List<SelectedOrderItem> items, Orders order)
        {
            int count = 0;
            var todayOrders = GetTodayOrderList(order);
            foreach (var item in items)
            {
                foreach (var realItem in todayOrders)
                {
                    if (realItem.OrderValue.Equals(item.OrderValue))
                    {
                        if (realItem.OrderCost == item.OrderCost)
                        {
                            count++;
                            continue;
                        }
                    }
                }
            }
            if (count == items.Count)
            {
                return true;
            }

            //记录user信息！！！！！！！！！！！！！！！！！！！！！！！
            return false;
        }

        //整理后的orders
        public static List<string> GetTotalOrders(List<UserInfo> userInfos, ref int cost, ref int count)
        {
            Dictionary<string, List<int>> orders = new Dictionary<string, List<int>>();
            foreach (var user in userInfos)
            {
                foreach (var order in user.UserOrderInfos)
                {
                    string userOrder = order.UserOrder;
                    if (!orders.ContainsKey(userOrder))
                    {
                        List<int> value = new List<int>();
                        value.Add(1);
                        value.Add(order.UserCost);
                        orders.Add(userOrder, value);
                    }
                    else
                    {
                        List<int> value = orders[userOrder];
                        value[0]++;
                        value[1] += order.UserCost;
                    }
                    count++;
                    cost += order.UserCost;
                }
            }

            List<string> result = new List<string>();
            foreach (var item in orders)
            {
                result.Add(item.Key + " " + item.Value[0] + "份 " + item.Value[1] + "元");
            }
            return result;
        }
    }

    public class MyPrincipal : IPrincipal
    {
        private IIdentity identity;
        private ArrayList roleList;

        public MyPrincipal(string userID, string password)
        {
            identity = new MyIdentity(userID, password);
            roleList = new ArrayList();
            if (identity.IsAuthenticated)
            {
                //"Admin"
                string role = DataBaseManager.GetUserInfo(userID, false).UserRole;
                if (!string.IsNullOrEmpty(role))
                {
                    roleList.Add(role);
                }
            }
            else
            {
                // do nothing
            }
        }

        public ArrayList RoleList
        {
            get
            {
                return roleList;
            }
        }

        public IIdentity Identity
        {
            get
            {
                // TODO:  添加 MyPrincipal.Identity getter 实现
                return identity;
            }
            set
            {
                identity = value;
            }
        }

        public bool IsInRole(string role)
        {
            // TODO:  添加 MyPrincipal.IsInRole 实现
            return roleList.Contains(role); ;
        }

    }

    public class MyIdentity : IIdentity
    {
        private string userID;
        private string password;

        public MyIdentity(string currentUserID, string currentPassword)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            userID = currentUserID;
            password = currentPassword;
        }

        private bool CanPass()
        {
            //这里朋友们可以根据自己的需要改为从数据库中验证用户名和密码，
            //这里为了方便我直接指定的字符串
            return Utility.ValidateUser(userID, password);
        }

        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }

        // IIdentity 成员
        public bool IsAuthenticated
        {
            get
            {
                return CanPass();
            }
        }

        public string Name
        {
            get
            {
                // TODO:  添加 MyIdentity.Name getter 实现
                return userID;
            }
        }

        //这个属性我们可以根据自己的需要来灵活使用,在本例中没有用到它
        public string AuthenticationType
        {
            get
            {
                // TODO:  添加 MyIdentity.AuthenticationType getter 实现
                return null;
            }
        }

    }

    public class CacheUser
    {
        //可以添加balance吗？能否被他人修改
        public string UserName { get; set; }

        public string DisplayName { get; set; }

        public string PassWord { get; set; }

        public bool IsAuthenticated { get; set; }

        public bool HasLocalPassword { get; set; }

        public bool IsAdmin { get; set; }

        public bool HasBalance { get; set; }

        public bool CanOrder { get; set; }

        public Orders WhatToEat { get; set; }

        public CacheUser()
        {
            var cacheUser = HttpContext.Current.Request.Cookies["UserName"];
            var cachePsw = HttpContext.Current.Request.Cookies["Password"];
            if (cacheUser != null && cachePsw != null)
            {
                if (cacheUser.Value != null && cachePsw.Value != null)
                {
                    UserName = cacheUser.Value.ToString();
                    PassWord = cachePsw.Value.ToString();
                    MyPrincipal principal = new MyPrincipal(UserName, PassWord);
                    IsAuthenticated = principal.Identity.IsAuthenticated;
                    IsAdmin = principal.IsInRole("Admin");
                    var user = DataBaseManager.GetUserInfo(UserName, false);
                    HasBalance = user.UserBalance > 0;
                    HasLocalPassword = PassWord != null;
                    DisplayName = user.DisplayName;
                    var adminInfo = DataBaseManager.GetAdminManagerInfo();
                    IsAdmin = adminInfo.Administrators.Contains(UserName) && IsAdmin;
                    CanOrder = adminInfo.IfCanOrder;
                    WhatToEat = adminInfo.WhatToEat;
                }
            }
        }

        public void ChangePwdOfCacheUser(string passWord)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            HttpCookie newpsw = new HttpCookie("Password", passWord);
            //var user = HttpContext.Current.Request.Cookies["UserName"];
            //if (user != null)
            //{
            //    newpsw.Expires = user.Expires;
            //}
            newpsw.Expires = cookies["Password"].Expires;
            cookies.Remove("Password");
            cookies.Add(newpsw);
        }
    }

    public class SelectedOrderItem
    {
        public string OrderText { get; set; }

        public string OrderValue { get; set; }

        public int OrderCost { get; set; }

        public string OrderTime { get; set; }

        public bool Selected { get; set; }
    }
}